<script lang="ts" setup>
// 点击菜单的时候
import {pushTo} from "@/router";
import {usePermissionStore} from "@/store/modules/permission";
import {MenuForRouter} from "@/api/sys/admin/menu/types";
import {useSysStore} from "@/store/modules/sys";
import {onBeforeRouteUpdate, useRoute} from "vue-router";

const route = useRoute()

const sysStore = useSysStore()
const {isFolded, isPhone, x, y} = storeToRefs(sysStore)
const permissionStore = usePermissionStore()
const {getDynamicRoutes} = permissionStore
const currentRoutes = getDynamicRoutes() as MenuForRouter[]


async function clickMenu(name: string) {
  if (isPhone.value) {
    isFolded.value = true
  }
  await pushTo({name})
}

// 显示那个折叠图标
const showOpen = ref(false)

function toFullScreen() {
  isFolded.value = !isFolded.value
  showOpen.value = false
}

/**
 * 加入一个reload函数
 */
const isRouterAlive = ref(true)
const reload = () => {
  isRouterAlive.value = false
  nextTick(() => {
    isRouterAlive.value = true
  })
}
provide('reload', reload)

watchEffect(() => {
  if (y.value >= 72) {
    if (x.value <= 20 && isFolded.value) {
      showOpen.value = true
    }
    if (x.value >= 240) {
      showOpen.value = false
    }
  }
})

onBeforeRouteUpdate((to, from, next) => {
  // console.log('路由发生变化:',to.path)
  next()
})
</script>
<template>
  <el-affix v-show="showOpen" :offset="120" class="absolute">
    <el-button link @click="toFullScreen" class="arrow arrow--big">
      <i-ep-caret-right/>
    </el-button>
  </el-affix>
  <el-container class="target">
    <Transition name="fade">
      <el-aside v-show="!isFolded">
        <x-card>
          <div class="expand">
            <el-button link @click="toFullScreen" class="arrow">
              <i-ep-ArrowLeftBold/>
            </el-button>
          </div>
          <el-menu
              :default-active="route.name"
              @select="clickMenu"
          >
            <x-menu v-for="item in currentRoutes" :route="item"/>
          </el-menu>
        </x-card>
      </el-aside>
    </Transition>
    <el-main class="mt-0!">
      <router-view v-if="isRouterAlive"/>
    </el-main>
  </el-container>
</template>
<style lang="scss" scoped>
.el-aside {
  width: 220px;
  position: absolute;
  z-index: 101;
}

@media (min-width: 50em) {
  .el-aside {
    width: 220px;
    position: relative;
    z-index: 0;
  }
}


.expand {
  position: absolute;
  top: 0.2em;
  right: 0.2em;
  z-index: 1;
}

.arrow {
  padding: 1em;
}

.arrow--big {
  box-shadow: 2px 2px 10px rgb(36, 70, 178);
  font-size: 1.2em;
  border-radius: 0 48% 48% 0;
  transition: all 0.2s;

  &:hover {
    transform: scaleX(1.3);
  }
}

.fade-enter-active, .fade-leave-active {
  transition: all 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  transform: translateX(-180px);
  opacity: 0;
  width: 0;
}
</style>